<template>
<div>
    <div class="e-form">
        <BillTop title="租赁计划详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="计划明细" name="changeDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="推荐租赁商" name="recommendedLessor" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.planLease" label-width="160px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                           <span>{{formData.planLease.billNo}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划日期：">
                                            <span>{{formData.planLease.billDate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="配置计划编号：">
                                            <span>{{formData.planLease.configurationPlanNo}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报人：">
                                            <span>{{ formData.planLease.recorder }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="费用合计（元）：">
                                            <span>{{ formData.planLease.totalCost }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="变更期数：">
                                            <span>{{ formData.planLease.number }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ userInfo.orgInfo.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ statusLable(formData.planLease.state) }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁类型：">
                                            <span>{{ formData.planLease.leaseType ? leaseTypeList[formData.planLease.leaseType].label :''}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>{{formData.planLease.currency}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item  label="租赁说明：">
                                        <span>{{formData.planLease.remarks}}</span>
                                    </el-form-item>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.planLease.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="formData.planLease.state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.planLease.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.planLease.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="formData.planLease.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.planLease.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.planLease.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="changeDetailCon" class="con">
                        <div class="tabs-title" id="changeDetail">计划明细</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="planConfigurationDtlList"
                                border
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': planConfigurationDtlList, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="70" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    align="center"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="120"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="100"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="租赁数量"
                                    width="100"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="租赁单价（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                               <el-table-column
                                    prop="enterExitCost"
                                    label="预计进退场费（元）"
                                    width="160"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="serviceTime"
                                    label="预计使用时间"
                                    width="120"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="预计金额（元）"
                                    width="130"
                                    align="right"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="预计进场时间"
                                    width="160"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="recommendedLessorCon" class="con">
                        <div class="tabs-title" id="recommendedLessor">推荐租赁商</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="recommendedLessor"
                                :data="rentalBusiness"
                                border
                                @selection-change="rentalTableSelect"
                                :row-class-name="tableRowClass"
                                v-sortTable="{ 'tableData': rentalBusiness, '_this': this, 'ref': 'recommendedLessor' }"
                            >
                                <el-table-column prop="equipmentName"  align="center" label="设备名称" min-width="200">
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="rentalUnit"
                                    label="出租单位"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="phone"
                                    width="160"
                                    align="center"
                                    label="联系方式"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    width="120"
                                    align="right"
                                    label="可租数量"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    width="120"
                                    align="center"
                                    label="计时单位"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="租赁单价（元）"
                                    width="150"
                                    align="right"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilityplan" />
                    </div>

                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                :data="changeHistoryTable"
                                border
                                ref="changeHistorySelect"
                                @selection-change="changeHistoryTableSelect"
                                v-sortTable="{ 'tableData': changeHistoryTable, '_this': this, 'ref': 'changeHistorySelect' }"
                            >
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{row}">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDeleteHistory(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="changeBillNo"  align="center" label="变更编号" min-width="200" show-overflow-tooltip class-name="blue-column">
                                    <template slot-scope="{ row }" >
                                        <span @click="tableDbShow(row)">{{row.changeBillNo}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="变更日期"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="机构"
                                    show-overflow-tooltip min-width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="变更期数"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{row}">
                                        <span>{{statusLable(row.state)}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="5012"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
        <div class="buttons" v-if="!isview">
            <ComExaButtons :auditState="auditState" :state="formData.planLease.state" @exas="exas" :isPrint="formData.planLease.state === 2" :founderId="formData.planLease.founderId" />
            <el-button size="small" class="btn-blue" @click="handleChange" v-if="statusLable(formData.planLease.state) === '已审核' &&statusLable(formData.planLease.state) !== '已作废'" v-debounce='3000'>变更</el-button>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</div>

</template>

<script>
import { mapState, mapMutations } from 'vuex'
import request from '@/api/equip/equipPlan.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, selectDataClient, webprintReport, showLoading } from '@/utils/common'
import requestAudit from '@/api/equip/common.js'
import count from '@/api/equip/equipPlanCount.js'
import { exas } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            tableData: [],
            ProcurementPlanVisible: false, //控制选择维修计划页面显示隐藏
            formData: {
                //配置计划基础信息
                'planLease': {
                    'auditCost': 0,
                    'auditTime': '',
                    'auditor': '',
                    'auditorId': '',
                    'baseCurId': '',
                    'baseCurName': '',
                    'baseCurRate': 0,
                    'baseCurTotalCost': 0,
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'changeBillId': '',
                    'changeBillNo': '',
                    'changeState': 0,
                    'changeTotalCost': 0,
                    'configurationPlanId': '',
                    'configurationPlanNo': '',
                    'currency': '',
                    'currencyId': '',
                    'esaId': '',
                    'founderId': '',
                    'founderName': '',
                    'isExcss': '',
                    'isTemporaryLease': '',
                    'leaseType': '',
                    'modifier': '',
                    'modifierId': '',
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'number': 0,
                    'orgId': '',
                    'orgName': '',
                    'recorder': '',
                    'recorderId': '',
                    'remarks': '',
                    'rmbId': '',
                    'rmbName': '',
                    'rmbRate': 0,
                    'rmbSumTotalCost': 0,
                    'settleAmount': 0,
                    'source': '',
                    'state': 0,
                    'totalCost': 0,
                    'version': 0,
                    'workId': ''
                }
            },
            planConfigurationDtlList: [], //计划明细
            planSelect: [], //计划明细选择项
            currentRowPlan: {}, //计划明细当前行数据
            rentalBusiness: [], //推荐租赁商
            rentalSelect: [], //推荐租赁商选择项
            currentRowRental: {}, //推荐租赁商当前行数据
            changeHistoryTable: [], //变更历史表格
            changeHistorySelect: [], //变更历史选择项
            auditHistoryTable: [],
            billid: this.$route.query.billid,
            userId: '',
            rules: {
                billDate: [
                    { required: true, message: '请选择日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: ['blur', 'change']  },
                ],
                leaseType: [
                    { required: true, message: '请选择租赁类型', trigger: ['blur', 'change'] },
                ],
                configurationPlanNo: [
                    { required: false, validator: (rule, value, callback)=>{
                        if(this.formData.planLease.leaseType !== '2' && !this.formData.planLease.configurationPlanNo) {
                            callback(new Error('请选择配置计划编号'))

                        }
                        else {
                            callback()
                        }
                    }, trigger: ['blur', 'change'] }
                ]
            },
            isDisabled: false,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 5012,  //配置计划
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 5012,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            oldConfigPlan: [], //从配置计划带过来的数据
            oldLeasePlan: [], //从租赁计划明细带过来的数据
            isview: false
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            leaseTypeList: state => state.equip.equipData.leaseTypeList, //租赁类型
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //推荐租赁商 设备名称下拉框
        leasePlanDtlLists () {
            return this.planConfigurationDtlList.filter(item=>{
                return item.changeType !== -1
            })

        },
        //当前单据状态
        state () {
            return this.formData.planLease.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        if(this.$route.query.isview === 'true' || this.$route.query.isview === 'false') {
            this.isview = JSON.parse(this.$route.query.isview)
        }
        this.getDicValue()
        this.userId = localStorage.getItem('userId')
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'changeDetail', 'recommendedLessor', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllHistory()
    },
    methods: {
        ...mapMutations([ 'setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'recommendedLessor':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.recommendedLessor.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }

                break
            case 'changeHistory':
                this.isBatch[2].flag = !this.isBatch[2].flag
                if(this.isBatch) {
                    this.isBatch[2].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[2].batch = '进入批量管理'
                }
                break
            }

        },
        //跳转在变更历史
        scorllHistory () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //去变更新增页面
        handleChange () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getInitLeaseBaseInfo(params).then(()=>{
                const billid = this.billid
                this.$router.push({
                    path: '/leasePlanChangeAdd',
                    query: { billid }
                })
            })

        },
        //去变更编辑页面
        tableEdit (billid) {
            this.$router.push({
                path: '/leasePlanChangeEdit',
                query: { billid }
            })
        },
        //变更查看页面
        tableDbShow (row) {
            if(row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/leasePlanChangeShow',
                    query: { billid: row.billId }
                })
            }else{
                this.auditParams.billId = row.billId
                this.auditParams.billType = '50121'
                requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                    this.auditState = res
                    if( this.auditState.canModify == true) {
                        this.$router.push({
                            path: '/leasePlanChangeEdit',
                            query: { billid: row.billId }
                        })
                    }else{
                        this.$router.push({
                            path: '/leasePlanChangeShow',
                            query: { billid: row.billId }
                        })
                    }
                })
            }
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getBusiness(),
                this.getChangeHistory(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            requestAudit.history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取基本信息数据
        getInfo () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getLeaseBaseInfo(params).then(res=>{
                this.formData.planLease = res
                this.isDisabled = res.leaseType === '2' ? true : false
                this.getPlanList()
            })
        },
        //获取计划明细数据
        getPlanList () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getLeasePlanInfo(params).then(res=>{
                res.planLeaseDtlList.forEach(item=>{
                    item.leasePlanDtlUUId = item.leasePlanDtlId
                    if(item.planDtlId) {
                        let obj = {
                            'planDtlId': item.planDtlId,
                            'quantity': item.quantity
                        }
                        this.oldConfigPlan.push(obj)
                    }
                })
                this.planConfigurationDtlList = res.planLeaseDtlList
                this.onUpCollect()
            })
        },
        //配置计划明细查询
        getConfigPlanList () {
            this.oldConfigPlan = []
            const params = {
                planId: this.formData.planLease.configurationPlanId,
                userId: this.userId
            }
            request.getConfiPlanInfo(params).then(res=>{
                for(let i = this.rentalBusiness.length; i > 0; i--) {
                    for(let j = 0;j < this.planConfigurationDtlList.length;j++) {
                        this.planConfigurationDtlList[j].changeType = -1
                        if(this.rentalBusiness[i - 1].leasePlanDtlId == this.planConfigurationDtlList[j].leasePlanDtlUUId) {
                            this.$set(this.rentalBusiness[i - 1], 'changeState', -1)
                        }
                    }
                }
                res.planConfigurationDtlList.forEach(item=>{
                    item.changeType = 1
                    item.billId = this.billid
                    item.leasePlanDtlUUId = item.leasePlanDtlId
                    let obj = {
                        'planDtlId': item.planDtlId,
                        'quantity': item.quantity
                    }
                    this.planConfigurationDtlList.push(item)
                    this.oldConfigPlan.push(obj)
                })
                this.onUpCollect()
            })
        },
        //获取推荐租赁商
        getBusiness () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getBusiness(params).then(res=>{
                res.forEach(item=>{
                    if(item.leasePlanDtlId) {
                        let obj = {
                            'leasePlanDtlId': item.leasePlanDtlId,
                            'quantity': item.quantity
                        }
                        this.oldLeasePlan.push(obj)
                    }
                })
                this.rentalBusiness = res
            })
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                planId: this.billid,
                userId: this.userId
            }
            request.getleaseChangeHistory(params).then(res=>{
                this.changeHistoryTable = res
            })
        },
        //币种切换
        currencyChange (val) {
            this.formData.planLease.currency = this.currencyForm.find(x=>x.value === val).label  //币种名称
            requestAudit.getRmbRate({  //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId
            }).then(res=>{
                if(res.rate === 1) {
                    this.formData.planLease.rmbRate = res.rate
                    this.formData.planLease.rmbId = res.currency
                }else{
                    this.formData.planLease.rmbRate = res.rate
                    this.formData.planLease.rmbId = res.rateId
                }

            }).catch(()=>{

            })
        },
        //租赁类型切换
        leaseTypeChange (val) {
            this.isDisabled = val === '2' ? true : false
            this.clientPop(
                'info',
                '切换租赁类型，将重新选则配置计划编号，是否继续？',
                ()=>{
                    this.formData.planLease.configurationPlanNo = ''
                })
        },
        // 弹窗选择配置计划编号
        selectPlanNo () {
            this.clientPop(
                'info',
                '重新选择后,将清空计划明细里面的数据，是否继续？',
                ()=>{
                    let ids = []
                    // ids = this.formData.planConfigurationDtlList.map(x=>x.accountId)
                    selectDataClient({
                        SelectServiceToken: '/facilityplan/get/configuration/plan', // 客户端对应方法名
                        IsSingleMode: true, // 是否单选 true 单选 false 多选
                        SelectedIDs: ids, // 已选中id
                        Title: '选择配置计划编号' // 标题
                    }).then(val => {
                        this.formData.planLease.configurationPlanNo = val[0].billNo
                        this.formData.planLease.configurationPlanId = val[0].billId
                        this.getConfigPlanList()
                    })
                }
            )

        },
        /* 计划明细 */
        //模拟添加一行
        selectEquip () {
            let obj = {
                'acceptedQuantity': null,
                'amount': null,
                'auditAmount': 0,
                'auditEnterExitCost': 0,
                'auditPrice': 0,
                'auditQuantity': 0,
                'auditUseTime': 0,
                'billId': this.billid,
                'billNo': '',
                'changeType': 1,
                'enterDate': '',
                'enterExitCost': null,
                'equipmentId': '',
                'equipmentName': '模拟选择的数据',
                'isUsed': '',
                'leasePlanDtlId': '',
                'newOldRate': 0,
                'oldState': 0,
                'oneLevelCategoryId': '',
                'oneLevelCategoryName': '',
                'price': null,
                'quantity': null,
                'rentalRemark': '',
                'rentalUnit': '',
                'rmbSumCost': 0,
                'scSumCost': 0,
                'serviceTime': null,
                'specificationModel': '测试',
                'state': null,
                'timeUnit': '',
                'unit': '台',
                'leasePlanDtlUUId': '' //前端生成id
            }
            //前端生成id
            this.$Ajax
                .httpGet({
                    url: '/uid/builder?num=1',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(res=>{
                    obj.leasePlanDtlUUId = res[0]
                })
            this.planConfigurationDtlList.push(obj)
        },
        //计算金额 = 金额 = 数量*单价*预计使用时间+预计进退场费
        onAmount  (row) {
            let obj = this.oldConfigPlan.find(x=>x.planDtlId === row.planDtlId)
            if(obj) {
                var oldQuantity = obj.quantity
            }
            if(row.quantity > oldQuantity ) {
                this.clientPop(
                    'err',
                    '不能大于配置计划建议租赁数',
                )
                row.quantity = +oldQuantity
            }
            row.amount = count.onLeaseAmount(row.quantity, row.price, row.serviceTime,  row.enterExitCost)
            this.onUpCollect()
        },
        //费用合计 = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.planLease.totalCost = null
            this.formData.planLease.totalCost = count.onLeaseUpCollect(this.planConfigurationDtlList)
        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.planConfigurationDtlList.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.timeUnit === '') {
                            let str = `请选择第 ${index + 1} 行的（计时单位）`
                            this.errorMsg.push(str)
                        }
                        if( item.quantity === '' || item.quantity === null) {
                            let str = `请填写第 ${index + 1} 行的（租赁数量）`
                            this.errorMsg.push(str)
                        }
                        if(item.price === null || item.price === '') {
                            let str = `请填写第 ${index + 1} 行的（租赁单价（元））`
                            this.errorMsg.push(str)
                        }
                        if(item.serviceTime === null || item.serviceTime === '') {
                            let str = `请填写第 ${index + 1} 行的（预计使用时间）`
                            this.errorMsg.push(str)
                        }
                        if(item.enterDate === '') {
                            let str = `请选择第 ${index + 1} 行的（预计进场时间）`
                            this.errorMsg.push(str)
                        }
                    }

                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }
            })

        },
        /* 推荐推荐租赁商 */
        //新增一行数据
        newRentalBusiness () {
            let obj = {
                'changeState': 1,
                'equipmentName': '',
                'billId': this.billid,
                'leasePlanDtlId': '',
                'quantity': null,
                'phone': '',
                'price': null,
                'rentalBusinessId': '',
                'rentalUnits': '',
                'specificationModel': '',
                'unit': '',
            }
            this.rentalBusiness.push(obj)
        },
        //选择计划明细数据
        handleSelectEquip (row, $index) {
            row.rentalUnit = ''
            row.phone = ''
            this.planConfigurationDtlList.forEach(item=>{
                if(item.leasePlanDtlUUId == row.leasePlanDtlId) {
                    let obj  = {
                        ...row,
                        ...item
                    }
                    this.$set(obj, 'leasePlanDtlId', obj.leasePlanDtlUUId)
                    this.$set(this.rentalBusiness, $index, obj)
                    this.rentalBusiness.forEach(item=>{
                        if(item.leasePlanDtlId) {
                            let obj = {
                                'leasePlanDtlId': item.leasePlanDtlId,
                                'quantity': item.quantity
                            }
                            this.oldLeasePlan.push(obj)
                        }
                    })
                }
            })

        },
        onQuantity  (row) {
            let obj = this.oldLeasePlan.find(x=>x.leasePlanDtlId === row.leasePlanDtlId)
            console.log(obj)
            if(obj) {
                var oldQuantity = obj.quantity
            }
            if(row.quantity > oldQuantity ) {
                this.clientPop(
                    'err',
                    '不能大于计划明细的租赁数量',
                )
                row.quantity = +oldQuantity
            }
        },
        //弹窗选择设备
        selectRentalEquip (row, $index) {
            this.current = row
            this.index = $index
            // 弹窗选择数据
            let ids = []
            // ids = this.formData.planConfigurationDtlList.map(x=>x.accountId)
            selectDataClient({
                SelectServiceToken: '/facilityplan/list/account/equipment', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '选择计划明细' // 标题
            }).then(val => {
                this.selectConfirm(val)
            })
        },
        //选择设备确认
        selectConfirm (data) {
            let obj  = {
                ...this.current,
                ...data[0]
            }
            this.$set(this.rentalBusiness, this.index, obj)
            if(!data) return false
            this.selectEquipVisible = false
        },
        //获取租赁商表格的选择项
        rentalTableSelect (selection) {
            this.rentalSelect = selection
        },
        //判断当前状态是否已修改
        curRentalChange (row) {
            if (row.rentalBusinessId) {
                if (row.changeState === 2) return
                this.currentRowRental = row
                this.currentRowRental.changeState = 2
            }
        },
        //如果是-1就隐藏
        tableRowRental ({ row }) {
            if(row.changeState === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        /*
            变更历史
        */
        //获取计划明细表格的选择项
        changeHistoryTableSelect (selection) {
            this.changeHistorySelect = selection
        },
        handleDeleteHistory (row) {

            if(row.state !== 0) {
                this.clientPop(
                    'info',
                    '只要草稿状态才可以删除！',
                )
            }else{
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    ()=>{
                        request.deleteLeaseChangeHistoy(row.billId).then(()=>{
                            this.clientPop('suc', '删除成功')
                            this.getChangeHistory()
                        })
                    }
                )
            }
        },
        //删除草稿状态的变更历史
        handleChangeHistory () {
            const length = this.changeHistorySelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.changeHistorySelect.forEach(item=>{
                    if(item.state !== 0) {
                        this.clientPop(
                            'info',
                            '只有草稿状态才可以删除！',
                        )
                        this.$refs.changeHistorySelect.clearSelection()
                    }else{
                        this.clientPop(
                            'info',
                            this.moreDeleteErr(length),
                            this.deleteChangeHistory
                        )
                    }
                })
            }
        },
        //批量或单独删除变更历史
        deleteChangeHistory () {
            let billids = []
            this.changeHistorySelect.forEach(item=>{
                if(item.state === 0) {
                    billids.push(item.billId)
                    request.leaseDelete(billids).then(()=>{
                        this.init()
                        this.clientPop('suc', '删除成功')
                        this.$refs.changeHistorySelect.clearSelection()
                    })
                }
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.updateLease(this.formData).then(()=>{
                    this.verifyTable().then(()=>{
                        this.a = this.planConfigurationDtlList
                        request.updateLeaseDetailInfo(this.planConfigurationDtlList).then(()=>{
                            this.getInfo()
                            this.getPlanList()
                            resolve()
                        }).catch(err=>{
                            this.setError('changeDetail')
                            reject(err)
                        })
                    }).catch(err=>{
                        this.setError('changeDetail')
                        reject(err)
                    })

                }).catch(err=>{
                    this.setError('baseInfo')
                    reject(err)
                })
            })
        },
        //计划明细（新增、编辑、删除）
        updateDetailInfo  () {
            return request.updateLeaseDetailInfo(this.planConfigurationDtlList).then(()=>{
                this.getInfo()
            })
        },
        //推荐租赁商（新增、编辑、删除）
        updateBusiness  () {
            return new Promise((resolve, reject)=>{
                return request.updateBusiness(this.rentalBusiness).then(()=>{
                    this.getBusiness()
                    resolve()
                }).catch(err=>{
                    this.setError('recommendedLessor')
                    reject(err)
                })
            })

        },
        //删除单据
        deleteBills () {
            request.leaseDelete(this.billid).then(()=>{
                this.$router.push('/leasePlanList')
            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
                this.updateBusiness()
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                })
                .catch(()=> {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        /*审核相关操作*/
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            requestAudit.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //返回列表
        handleList () {
            this.$router.push({
                path: '/leasePlanList',
                query: { billid: this.billid }
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/leasePlanList')
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 0)
            if (arg === 'print') {
                const printData = async ()=>{
                    showLoading()
                    try{
                        const  params =  {
                            'reportTitle': '设备租赁计划单', //报表名
                            'orgName': this.userInfo.orgInfo.orgName, //单据机构
                            'reportQRUri': '', //报表内容URI
                            'billNo': this.formData.billId, //单据编码
                            'summaryInfoItems': [ //基本信息
                                {
                                    'label': '费用合计',
                                    'value': this.formData.planLease.totalCost,
                                    'isFullRow': true //是否占整行
                                },
                                {
                                    'label': '计划日期',
                                    'value': this.formData.planLease.billDate,
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '临租',
                                    'value': this.formData.planLease.leaseType ? this.leaseTypeList[this.formData.planLease.leaseType].label : '',
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '备注信息',
                                    'value': this.formData.planLease.remarks,
                                    'isFullRow': true //是否占整行
                                },
                            ],
                            'tables': [ //表格
                                {
                                    'tableTitle': '表名',
                                    'tableContent': {
                                        '序号': 'index',
                                        '设备名称': 'equipmentName',
                                        '规格型号': 'specificationModel',
                                        '单位': 'timeUnit',
                                        '数量': 'quantity',
                                        '租赁单价': 'price',
                                        '金额': 'enterExitCost',
                                        // '新旧程度%': '规格型号',
                                        // '计时单位': '规格型号',
                                        '预计使用时间': 'serviceTime',
                                        '预计进退场费用': 'enterExitCost',
                                        '预计进场时间': 'enterDate',
                                    },
                                    'tableData': this.planConfigurationDtlList, //表格数据
                                },
                                {
                                    'tableTitle': '建议租赁商',
                                    'tableContent': {
                                        '序号': 'index',
                                        '设备名称': 'equipmentName',
                                        '规格型号': 'specificationModel',
                                        '出租单位': 'rentalUnit',
                                        '联系方式': 'phone',
                                        '可租数量': 'quantity',
                                        '计时单位': 'timeUnit',
                                        '租赁价格': 'price',
                                    },
                                    'tableData': this.rentalBusiness, //表格数据
                                },
                                {
                                    'tableTitle': '审核历史',
                                    'tableContent': {
                                        '审核级次': 'unitName',
                                        '审核人': 'assignUser',
                                        '审核岗位': 'userTitle',
                                        '审核时间': 'completeTime',
                                        '审核意见': 'opinion',
                                    },
                                    'tableData': this.auditHistoryTable, //表格数据
                                }
                            ],
                        }

                        hideLoading()
                        return params
                    }catch(err) {
                        console.log(err)
                        this.clientPop('err', '打印失败')
                        hideLoading()
                    }
                }
                const data = await printData()
                webprintReport(data)
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
</style>
